/**
 * @program: smart-school
 * @description:
 * @author: Qing Miao Dan Xie
 * @create: 2022-05-30 10:56
 **/
package org.jeecg.modules.analysisachievement.reports.utils;

import java.net.URLEncoder;

import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.analysisachievement.reports.service.AnalysisReportService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

@Slf4j
public class Export {
    private Configuration configuration;
    private String encoding;
    private String exportPath = "D:\\test\\";

    /**
     * 构造函数
     * 配置模板路径
     *
     * @param encoding
     */
    public Export(String encoding) {
        this.encoding = encoding;
        configuration = new Configuration();
        configuration.setDefaultEncoding(encoding);
        configuration.setClassForTemplateLoading(this.getClass(), "/templates");
    }

    /**
     * 获取模板
     *
     * @param name
     * @return
     * @throws Exception
     */
    public Template getTemplate(String name) throws Exception {
        configuration.setClassForTemplateLoading(this.getClass(), "/templates/");
        configuration.setClassicCompatible(true);
        return configuration.getTemplate(name);
    }

    /**
     * 导出word文档到指定目录
     *
     * @param fileName
     * @param tplName
     * @param data
     * @throws Exception
     */
    public void exportDocFile(String fileName, String tplName, Map<String, Object> data) throws Exception {
        //如果目录不存在，则创建目录
        File exportDirs = new File(exportPath);
        if (!exportDirs.exists()) {
            exportDirs.mkdirs();
        }
        Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(exportPath + fileName), encoding));
        getTemplate(tplName).process(data, writer);
    }

    /**
     * 导出word文档到客户端
     *
     * @param response
     * @param fileName
     * @param tplName
     * @param data
     * @throws Exception
     */
    public void export(HttpServletResponse response, String fileName, String tplName, Map<String, Object> data) throws Exception {
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/msword");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.setHeader("Access-Control-Allow-Origin", "*");
        // 把本地文件发送给客户端
        Writer out = response.getWriter();
        Template template = getTemplate(tplName);
        template.process(data, out);
        out.close();
    }

}
